package com.mdd.admin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.service.ILegalConfigSettingService;
import com.mdd.admin.validate.LegalConfigSettingCreateValidate;
import com.mdd.admin.validate.LegalConfigSettingSaveValidate;
import com.mdd.admin.validate.LegalConfigSettingSearchValidate;
import com.mdd.admin.validate.LegalConfigSettingUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.LegalConfigSettingDetailVo;
import com.mdd.admin.vo.LegalConfigSettingListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.LegalConfigSetting;
import com.mdd.common.mapper.LegalConfigSettingMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 基础配置实现类
 * @author LikeAdmin
 */
@Service
public class LegalConfigSettingServiceImpl implements ILegalConfigSettingService {
        
    @Resource
    LegalConfigSettingMapper legalConfigSettingMapper;

    /**
     * 基础配置列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<LegalConfigSettingListedVo>
     */
    @Override
    public PageResult<LegalConfigSettingListedVo> list(PageValidate pageValidate, LegalConfigSettingSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<LegalConfigSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        legalConfigSettingMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:configName@config_name:str",
            "=:code:str",
            "=:configParams@config_params:str",
            "=:configType@config_type:int",
        });

        IPage<LegalConfigSetting> iPage = legalConfigSettingMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<LegalConfigSettingListedVo> list = new LinkedList<>();
        for(LegalConfigSetting item : iPage.getRecords()) {
            LegalConfigSettingListedVo vo = new LegalConfigSettingListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public Map<String, Object> list2(Integer type) {
        Map<String, Object> map = new HashMap<>();
        List<LegalConfigSetting> list = legalConfigSettingMapper.selectList(new QueryWrapper<>());
        if (CollectionUtils.isNotEmpty(list)) {
            if (type == 1) {
                for (LegalConfigSetting item : list) {
                    if (item.getCode().equals("loop_img_setting")) {
                        map.put("loop_img_setting", item.getConfigParams());
                    } else if (item.getCode().equals("fixed_ad_img")) {
                        map.put("fixed_ad_img", item.getConfigParams());
                    } else if (item.getCode().equals("service_call")) {
                        map.put("service_call", item.getConfigParams());
                    } else if (item.getCode().equals("platform_commission_rate")) {
                        map.put("platform_commission_rate", item.getConfigParams());
                    } else if (item.getCode().equals("withdraw_rate")) {
                        map.put("withdraw_rate", item.getConfigParams());
                    } else if (item.getCode().equals("lawyer_price")) {
                        map.put("lawyer_price", item.getConfigParams());
                    } else if (item.getCode().equals("customer_compacrt_ageing")) {
                        map.put("customer_compacrt_ageing", item.getConfigParams());
                    } else if (item.getCode().equals("ai_user_money")) {
                        map.put("ai_user_money", item.getConfigParams());
                    }
                }
            } else if (type == 2) {
                for (LegalConfigSetting item : list) {
                    if (item.getCode().equals("newland_mercId")) {
                        map.put("newland_mercId", item.getConfigParams());
                    } else if (item.getCode().equals("newland_orgNo")) {
                        map.put("newland_orgNo", item.getConfigParams());
                    } else if (item.getCode().equals("newland_trmNo")) {
                        map.put("newland_trmNo", item.getConfigParams());
                    } else if (item.getCode().equals("newland_secret")) {
                        map.put("newland_secret", item.getConfigParams());
                    }
                }
            } else if (type == 3) {
                for (LegalConfigSetting item : list) {
                    if (item.getCode().equals("jump_loop_imgs")) {
                        String configParams = item.getConfigParams();
                        List<Map> maps = JSON.parseArray(configParams, Map.class);
                        map.put("jump_loop_imgs", maps);
                    }
                }
            }
        }
        return map;
    }

    /**
     * 基础配置详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return LegalConfigSetting
     */
    @Override
    public LegalConfigSettingDetailVo detail(Integer id) {
        LegalConfigSetting model = legalConfigSettingMapper.selectOne(
                new QueryWrapper<LegalConfigSetting>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        LegalConfigSettingDetailVo vo = new LegalConfigSettingDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 基础配置新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(LegalConfigSettingCreateValidate createValidate) {
        LegalConfigSetting model = new LegalConfigSetting();
        model.setConfigName(createValidate.getConfigName());
        model.setCode(createValidate.getCode());
        model.setConfigParams(createValidate.getConfigParams());
        model.setConfigType(createValidate.getConfigType());
        legalConfigSettingMapper.insert(model);
    }

    /**
     * 基础配置编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(LegalConfigSettingUpdateValidate updateValidate) {
        LegalConfigSetting model = legalConfigSettingMapper.selectOne(
                new QueryWrapper<LegalConfigSetting>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setConfigName(updateValidate.getConfigName());
        model.setCode(updateValidate.getCode());
        model.setConfigParams(updateValidate.getConfigParams());
        model.setConfigType(updateValidate.getConfigType());
        legalConfigSettingMapper.updateById(model);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSetting(LegalConfigSettingSaveValidate updateValidate) {
        if (updateValidate.getType() == 1) {
            saveSettings("ai_user_money", updateValidate.getAi_user_money());
            saveSettings("customer_compacrt_ageing", updateValidate.getCustomer_compacrt_ageing());
            saveSettings("fixed_ad_img", updateValidate.getFixed_ad_img());
            saveSettings("lawyer_price", updateValidate.getLawyer_price());
            saveSettings("loop_img_setting", updateValidate.getLoop_img_setting());
            saveSettings("platform_commission_rate", updateValidate.getPlatform_commission_rate());
            saveSettings("service_call", updateValidate.getService_call());
            saveSettings("withdraw_rate", updateValidate.getWithdraw_rate());
        } else if (updateValidate.getType() == 2) {
            saveSettings("newland_mercId", updateValidate.getNewland_mercId());
            saveSettings("newland_orgNo", updateValidate.getNewland_orgNo());
            saveSettings("newland_trmNo", updateValidate.getNewland_trmNo());
            saveSettings("newland_secret", updateValidate.getNewland_secret());
        } else if (updateValidate.getType() == 3) {
            saveSettings("jump_loop_imgs", updateValidate.getJump_loop_imgs());
        }
    }

    private void saveSettings(String key, String value) {
        LegalConfigSetting item = legalConfigSettingMapper.selectOne(new QueryWrapper<LegalConfigSetting>()
                .eq("code", key)
                .last("limit 1"));
        item.setConfigParams(value);
        legalConfigSettingMapper.updateById(item);
    }

    /**
     * 基础配置删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        LegalConfigSetting model = legalConfigSettingMapper.selectOne(
                new QueryWrapper<LegalConfigSetting>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        legalConfigSettingMapper.delete(new QueryWrapper<LegalConfigSetting>().eq("id", id));
    }

}
